<template>
    <el-row class="header_login">
        <el-col :span="24">
            <el-row justify="space-between" align="middle">
                <el-image style="width: auto; height: auto;" :src="imgUrl" />
                <el-input v-model="takeoutName" style="width: 30%;height: 50%;margin-right: 2%;" placeholder="搜索外卖..."
                    size="large">
                    <template #append>
                        <el-button :icon="Search" @click="searchTakeout" />
                    </template>
                </el-input>
            </el-row>
        </el-col>
    </el-row>
    <el-row style="padding: 2%;">
        <el-col :span="24">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item to="/">返回</el-breadcrumb-item>
                <el-breadcrumb-item>
                    {{ takeout?.takeout_name }}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </el-col>
    </el-row>
    <el-row class="commodity_body">
        <el-col :span="10" align="middle">
            <el-image :src="`${takeout?.takeout_portrait}`" style="width: 60%;"></el-image>
        </el-col>
        <el-col :span="14">
            <el-row type="flex" align="middle">
                <el-col :span="24">
                    <el-text style="font-size: xx-large;font-weight: bold;"> {{ takeout?.takeout_name
                        }}</el-text>
                </el-col>
                <el-col :span="24" style="margin-top: 1%;">
                    <el-text style="font-size: medium;font-weight: bold;color: gray;">
                        {{ takeout?.introduce }}
                    </el-text>
                </el-col>
                <el-col :span="23" style="background-color: gainsboro;padding: 2%; margin-top: 1%;">
                    <el-text style="font-size: x-large;font-weight: bold;color: red;">价格</el-text>
                    <el-text style="font-size: xx-large;font-weight: bold;color: red;"> ¥ {{ takeout?.price
                        }}</el-text>
                </el-col>
                <el-col :span="23">
                    <el-divider />
                </el-col>
                <el-col :span="24" style="margin-top: 1%;">
                    <el-text style="font-size: medium;"> 外卖编码：{{ takeout?.id }}</el-text>
                </el-col>
                <el-col :span="24" style="margin-top: 1%;">
                    <el-text style="font-size: medium;"> 上架时间：{{
                        takeout?.create_time
                        }}</el-text>
                </el-col>
                <el-col :span="12" style="margin-top: 1%;">
                    <el-text style="font-size: medium;"> 商家名称：{{ store?.store_name }}</el-text>
                </el-col>
                <el-col :span="12" style="margin-top: 1%;">
                    <el-text style="font-size: medium;"> 地址：{{ store?.address }}</el-text>
                </el-col>
                <el-col :span="23">
                    <el-divider />
                </el-col>
                <el-col :span="24">
                    <el-text style="font-size: medium;"> 已选择外卖：</el-text>
                    <el-text style="font-size: medium;color: red;"> {{ takeout?.takeout_name }}</el-text>
                </el-col>
                <el-col :span="24" style="margin-top: 1%;">
                    <el-text style="font-size: medium;"> 份数：</el-text>
                    <el-input-number v-model="count" :min="0" @change="handleChange" />
                </el-col>
                <el-col :span="24" style="margin-top: 7%;">
                    <el-button type="danger" plain style="width: 20%;padding: 3%;" @click="pay">立即购买(¥{{
                        price }})</el-button>
                    <el-button type="warning" plain style="width: 20%;padding: 3%;" @click="addMenu">加入菜单</el-button>
                </el-col>
                <el-col :span="24" style="margin-top: 2%;">
                    <el-text style="font-size:small;color: gray;">
                        温馨提示 提前设置默认收货地址，购买更顺利~
                    </el-text>
                </el-col>
            </el-row>
        </el-col>
        <el-backtop :bottom="100" :right="20" style="
        height: 60px;
        width: 60px;
        background-color: #fbaf5a;
        box-shadow: var(--el-box-shadow-lighter);
        text-align: center;
        line-height: 30px;
        color: #ffffff;
        border-radius: 50px;
      ">
        </el-backtop>
        <el-dialog v-model="dialogVisible" title="提示" width="500" :before-close="handleClose">
            <span>请先登陆</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="goLogin">
                        登入
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </el-row>
    <el-row justify="center" align="middle" style="margin-top: 5%;">
        <el-col :span="20">
            <el-divider content-position="left">
                <el-text style="font-size: medium;font-weight: bold;">
                    评论留言
                </el-text>
            </el-divider>
        </el-col>
        <el-col :span="4" align="center">
            <el-button @click="isLogin">
                我来写写评论
            </el-button>
        </el-col>
        <el-col :span="23" style="margin-bottom: 5%;">
            <el-space wrap fill style="width: 100%;">
                <div v-for="item in discussList" :key="item.id">
                    <el-card shadow="hover" style="width: 100%;;border-radius: 5px;">
                        <el-row align="middle" justify="center">
                            <el-col :span="1">
                                <el-image :src="`${item.user.head_portrait!}`"
                                    style="width: 40px;height: 40px;border-radius: 50px;" fit="contain" />
                            </el-col>
                            <el-col :span="23">
                                <el-row style="width: 100%;">
                                    <el-col :span="24" align="start">
                                        <el-text style="font-size: medium;" line-clamp="1">{{
                                            item.user.username
                                        }}</el-text>
                                    </el-col>
                                    <el-col :span="24" align="start">
                                        <el-text style="font-size: small;" line-clamp="1">{{
                                            item.create_time
                                        }}</el-text>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <el-col :span="24" align="start"
                                style="background-color: bisque; border-radius: 5px; margin-top: 1%;padding: 1%;">
                                <el-text style="color: gray;">评论：{{ item?.content
                                    }}</el-text>
                            </el-col>
                        </el-row>
                    </el-card>
                </div>
            </el-space>
        </el-col>
    </el-row>
    <el-dialog v-model="dialogFormVisible" title="评论" width="500">
        <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" status-icon :label-position="labelPosition">
            <el-form-item prop="content">
                <el-input v-model="ruleForm.content" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消评论</el-button>
                <el-button type="primary" @click="discuss">
                    发送评论
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>


<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { Search } from '@element-plus/icons-vue';
import { imgUrl } from '../assets/common/Constants.ts';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, FormInstance, FormProps, FormRules } from 'element-plus';
import { TakeoutModel } from '../assets/models/Takeout.ts';
import { agcApis } from '../assets/apis/AgcApis.ts';
import { MenuModel } from '../assets/models/Menu.ts';
import { takeoutApis } from '../assets/apis/TakeoutApis.ts';
import { StoreModel } from '../assets/models/Store.ts';
import { storeApis } from '../assets/apis/StoreApis.ts';
import { DiscussModel } from '../assets/models/Discuss.ts';
import { userInfoStore } from '../assets/userStore/userStore.ts';
import { discussApis } from '../assets/apis/DiscussApis.ts';
import { menuApis } from '../assets/apis/MenuApis.ts';
import { addressApis } from '../assets/apis/AddressApis.ts';
import { AddressModel } from '../assets/models/Address.ts';

const labelPosition = ref<FormProps['labelPosition']>('top');
const router = useRouter();
const route = useRoute();
const takeoutName = ref<string>();
const takeout = ref<TakeoutModel>();
const count = ref<number>(0);
const price = ref<number>(0);
const store = ref<StoreModel>();
const dialogVisible = ref<boolean>(false);
const dialogFormVisible = ref(false);
const userStore = userInfoStore();
const discussList = ref<Array<DiscussModel>>();
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<DiscussModel>({
    content: '',
    user: userStore.id,
    takeout: Number(route.query.id)
});

const rules = reactive<FormRules<DiscussModel>>({
    content: [
        {
            required: true,
            message: '请输入评论',
            trigger: 'change'
        }
    ]
});

onMounted(() => {
    let id: number = Number(route.query.id);
    takeoutApis.queryTakeout(id)
        .then((value: TakeoutModel) => {
            if (value) {
                takeout.value = value;
                storeApis.queryTakeoutStore(value.store!)
                    .then((value: StoreModel) => {
                        if (value) {
                            store.value = value;
                        }
                    })
            }
        })
    discussApis.queryDiscuss(id)
        .then((value: Array<DiscussModel>) => {
            if (value) {
                discussList.value = value;
            }
        })
})

const handleClose = (done: () => void) => {
    ElMessageBox.confirm('关闭提示')
        .then(() => {
            done()
        })
        .catch(() => {
            // catch error
        })
}

const goLogin = () => {
    dialogVisible.value = false;
    router.push({
        path: "/login"
    })
}

const handleChange = (value: number) => {
    if (takeout.value) {
        count.value = value;
        price.value = value * takeout.value.price!
    }
}

const addMenu = () => {
    agcApis.getCurrectUser().then((user) => {
        if (user && takeout.value) {
            if (count.value <= 0) {
                ElMessage.warning('请至少选择1件商品！')
            } else {
                if (takeout.value.id) {
                    let menu: MenuModel = {
                        takeout: takeout.value.id,
                        user: user.getUid(),
                        count: count.value,
                        price: price.value!
                    }
                    menuApis.insertMenu(menu)
                        .then((value: boolean) => {
                            if (value) {
                                ElMessage.success('添加成功');
                            } else {
                                ElMessage.error('添加失败');
                            }
                        })
                }
            }
        } else {
            dialogVisible.value = true;
        }
    })
}
const isLogin = () => {
    agcApis.getCurrectUser()
        .then((user) => {
            if (user) {
                dialogFormVisible.value = true;
            } else {
                dialogVisible.value = true;
            }
        })
}

const pay = () => {
    agcApis.getCurrectUser().then((user) => {
        if (user) {
            if (count.value <= 0) {
                ElMessage.warning('请至少选择1件商品！')
            } else {
                addressApis.queryDefaultAddress(userStore.id)
                    .then((value: AddressModel | undefined) => {
                        if (value) {
                            router.push({
                                path: "/order",
                                query: {
                                    id: takeout.value?.id,
                                    count: count.value,
                                    price: price.value!,
                                    way: 0
                                }
                            })
                        } else {
                            ElMessage.warning('请先设置默认地址');
                        }
                    })
            }

        } else {
            dialogVisible.value = true;
        }
    })
}

const discuss = () => {
    dialogFormVisible.value = false;
    discussApis.sendDiscuss(ruleForm)
        .then((value: boolean) => {
            if (value) {
                ElMessage.success('评论成功');
                discussApis.queryDiscuss(takeout.value?.id!)
                    .then((value: Array<DiscussModel>) => {
                        if (value) {
                            discussList.value = value;
                        }
                    })
            } else {
                ElMessage.error('评论失败');
            }
        })
}


const searchTakeout = () => {
    router.push({
        path: '/search',
        query: {
            way: 0,
            arg: takeoutName.value
        }
    })
}
</script>
<style>
.commodity_body {
    height: 100%;
    width: 100%;
}

.header_login {
    width: 100%;
    height: 90px;
    background-color: #fbaf5a;
    padding: 20px;
}
</style>
